<?php

namespace app\index\controller;

use app\common\CommonResponse;
use app\index\validate\WorkValidate;
use think\App;
use think\Request;

class Work extends Base
{
    protected $userModel;
    protected $workModel;

    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->userModel=new \app\common\model\User();
        $this->workModel=new \app\common\model\Work();
    }

    /** 工作经历列表
     * @return void
     */
    public function historyWorks(){
        $historyWorks = $this->workModel->where("user_id",$this->user['id'])->order("start_time")->select();
        $this->assign("works",$historyWorks);
        return $this->fetch();
    }

    /** 删除工作经历
     * @param Request $request
     * @return \think\response\Json
     * @throws \Exception
     */
    public function delWork(Request $request){
        if(!$request->post("id")){
            return json(CommonResponse::error("参数为空"));
        }
        $deleteRes = $this->workModel::get($request->post("id"))->delete();
        if($deleteRes){
            return json(CommonResponse::success("删除成功"));
        }
        return json(CommonResponse::error("删除失败"));

    }

    public function addWork(Request $request){
        if($request->isPost()){
            $formData=$request->post();
            $workValidate = new WorkValidate();
            if(!$workValidate->check($formData)){
                return $this->error($workValidate->getError());
            }
            $formData['user_id']=$this->user['id'];
            $formData['start_time']= strtotime($formData['start_time']);
            $formData['end_time']= strtotime($formData['end_time']);
            $save = $this->workModel->save($formData);
            if(!$save){
                return $this->error("保存失败");
            }
            return $this->success("保存成功","index/work/historyWorks");
        }
        return $this->fetch();

    }
}